package com.meng.controller;

import com.meng.service.UserService;
import com.meng.util.ResultUtil;
import com.meng.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("sys")
public class UserController {

    @Autowired
    private UserService userService;


  /*  //跳转到登录页面
    @RequestMapping("tologin")
    public String toLogin(){
         return "/views/user/login.html";
    }*/

//    @RequestMapping("/success")
//    public String loginsuccess(){
//        return "/views";
//    }
    //登录
    @RequestMapping("/login")
    @ResponseBody
    public ResultUtil login(UserVo userVo,HttpServletRequest request, String username, String password) throws Exception{

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        Subject subject = SecurityUtils.getSubject();
          if (username ==null || username=="" && password ==null || password==""){
              return ResultUtil.error("用户名或密码不能为空");
          }
          try {
              subject.login(token);
              System.out.println("认证成功");
          }catch (UnknownAccountException e){
               return ResultUtil.error("账户不存在");
          }catch (IncorrectCredentialsException e){

               return ResultUtil.error("密码错误");
          }
          return ResultUtil.success("登录成功");
    }

    //登出
    @RequestMapping("/loginout")
    @ResponseBody
    public ResultUtil loginout() {
        SecurityUtils.getSubject().logout();
        return ResultUtil.success("退出成功");
    }

    //获取用户表单信息
    @RequestMapping("/showuser")
    @ResponseBody
    public ResultUtil showuserList(Integer page, Integer limit){

        ResultUtil resultUtil = userService.selUser(page,limit);

       // System.out.println(resultUtil);
        return resultUtil;
    }



}
